<template>
  <!-- 值：选择变量 -->
  <div class="flex items-center w-full">
    <mci-select
      v-model="selectVal"
      :list="parametersOptions"
      class="w-full"
      :multiple="props.mul"
      :collapse-tags="true"
      :filterable="true"
      collapse-tags-tooltip
      @change="handleChange"
    >
      <mci-option v-for="option in parametersOptions" :key="option.varName" :label="option.label" :value="option.value" />
    </mci-select>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue';
import { MciSelect, MciOption } from '@/components/base';
import { conditionsKey } from '../../data';
const { variableOptions } = inject(conditionsKey);

const props = defineProps<{
  condValue: any;
  mul: boolean;
}>();
const emit = defineEmits(['valueChange']);

const selectVal = ref<any>();

const buildOption = (parameters: any) => {
  const uniqueValues = new Set();

  // 过滤并收集不为空、且label与value都存在的项
  const filteredItems = parameters
    .filter((item: { label: any; value: any; }) => item && item.label && item.value)
    .filter((item: { value: unknown; }) => {
      // 如果 Set 中没有这个 value，则添加并返回 true，允许此次过滤通过
      const isUnique = !uniqueValues.has(item.value);
      if (isUnique) {
        uniqueValues.add(item.value);
      }
      return isUnique;
    });

  return filteredItems;
};

// 初始化值
const buildValue = (oldValue?: any) => {
  if (oldValue && props.mul && typeof oldValue === 'string') {
    try {
      selectVal.value = JSON.parse(oldValue);
    } catch (error) {
      console.error(error);
    }
  } else {
    selectVal.value = oldValue;
  }
};
buildValue(props.condValue);

const parametersOptions = ref<any[]>([]);
parametersOptions.value = buildOption(variableOptions.variableOptions);
watch(
  [() => props.condValue, () => props.mul, () => variableOptions.variableOptions],
  ([newCondValue, , newParameters]) => {
    selectVal.value = newCondValue;
    parametersOptions.value = buildOption(newParameters);
  },
  { deep: true }
);

const handleChange = (val: any) => {
  emit('valueChange', val);
};
</script>
